import datetime
import json

from django.contrib.auth import authenticate
from django.http import JsonResponse
from django.utils import timezone
from django.views import View
from rest_framework_jwt.utils import jwt_decode_handler

from question.models import Reply, Question
from question.utils import get_user_dict
from users.models import User


class ReplyView(View):

    """回答问题"""
    def post(self, request):

        # 获取用户信息
        user_dict = get_user_dict(request)

        # 判断用户是否合法
        if user_dict:
            # 获取用户
            user = User.objects.get(id=user_dict['user_id'])
        else:
            return JsonResponse({'message': '未登录', 'success': False})

        data_dict = json.loads(request.body.decode())
        # 获取数据
        problem_id = data_dict.get('problem', None)
        content = data_dict.get('content', '')
        content_type = data_dict.get('type', None)
        parent = data_dict.get('parent', None)

        # 验证数据
        if not all([problem_id, content]):
            return JsonResponse({'message': '缺少参数', 'success': False})

        try:
            if content_type == 0:
                # 评论问题
                reply = Reply.objects.create(type=0, problem_id=problem_id, content=content, user_id=user.id)

            elif content_type == 1:
                # 获取父级对象
                parent_obj = Reply.objects.get(id=parent)

                # 评论回答
                reply = Reply.objects.create(type=1, problem_id=problem_id, content=content,
                                             parent=parent_obj, user_id=user.id)

            elif content_type == 2:
                # 回答问题
                reply = Reply.objects.create(type=2, problem_id=problem_id, content=content, user_id=user.id)

            else:
                return JsonResponse({'message': '参数错误', 'success': False})

        except Exception as e:
            return JsonResponse({'message': '保存错误', 'success': False})

        # 评论数 +1
        question = Question.objects.get(id=problem_id)
        question.reply += 1
        question.replyname = user.username
        question.replytime = timezone.now()
        question.save()

        return JsonResponse({'message': 'ok', 'success': True})


# 回答有用
class ReplyIDUsefulView(View):
    def put(self, request, id):
        try:
            reply = Reply.objects.get(id=id)
        except Exception as e:
            return JsonResponse({'message': '数据库错误', 'success': False})

        reply.useful_count += 1
        reply.save()
        return JsonResponse({'message': 'ok', 'success': True})


# 回答没用
class ReplyIDUnusefulView(View):
    def put(self, request, id):
        try:
            reply = Reply.objects.get(id=id)
            reply.useful_count -= 1

            if reply.useful_count < 0:
                reply.useful_count = 0
                reply.save()
                return JsonResponse({'message': '已经最小了, 你和我有仇吗?', 'success': False})

            reply.save()
        except Exception as e:
            return JsonResponse({'message': '数据库错误', 'success': False})

        return JsonResponse({'message': 'ok', 'success': True})

